/*
 * @Author: 何 海深 813936564@qq.com
 * @Date: 2023-12-01 11:44:03
 * @LastEditors: 何 海深 813936564@qq.com
 * @LastEditTime: 2024-03-27 11:15:54
 * @FilePath: \vue-project\src\hooks\userOutLogin\userOutLoginIndex.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import $https from '@/api/modules/userApi'
// 省统一身份退出
export const exitSystemClearInfo = async () => {
  const jumpUrl =
    location.host === '130.120.3.108'
      ? 'https://xtbg.digitalgd.com.cn'
      : 'https://xtbg.gdzwfw.gov.cn'
  const backUrl = `${location.protocol}//${location.host}/pymbp/login#/`
  window.location.href = `${jumpUrl}/zwrz/rz/sso/logout?client_id=zwrz_pyczczl&backurl=${decodeURIComponent(
    backUrl
  )}`
}
//  退出系统（中台登录）
export const exitSystemJump = async () => {
  if (import.meta.env.MODE === 'development') {
    window.open('http://130.120.3.108:8000/login/#/?backurl=http://127.0.0.1:5173/#/', '_self')
  } else {
    window.open(
      `${location.origin}/login/#/?backurl=${location.origin}/fgw-qkj-one-map/#/`,
      '_self'
    )
  }
}
// 处理退出系统
type LogOutType = 'justJump' | 'needRemove'
export const doExitSystem = async (loginType: LogOutType | undefined = 'justJump') => {
  if (loginType || loginType === 'needRemove') {
    const loginOutSuccess = await doLoginOut()
    if (!loginOutSuccess) {
      return false
    }
  }
  sessionStorage.clear() // 清除sessionStorage缓存
  localStorage.clear() // 清除localStorage缓存
  // eslint-disable-next-line no-useless-escape
  const keys = document.cookie.match(/[^ =;]+(?=\=)/g)
  if (keys) {
    // 清除cookie
    for (let i = keys.length; i--; ) {
      document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString()
    }
  }
  const casEnable = JSON.parse(localStorage.getItem('ststemloginType') as string)
  if (casEnable) {
    // 省统一退出
    exitSystemClearInfo()
    return true
  } else {
    // 中台退出
    doExitSystem()
    return true
  }
}

/**
 * @description: 调用退出登录接口
 * @return {*}
 */
export const doLoginOut = async (): Promise<boolean> => {
  return new Promise((reslove) => {
    $https
      .loginOut()
      .then((res) => {
        if (res.success) {
          reslove(true)
        } else {
          reslove(false)
        }
      })
      .catch((error) => {
        if (error) {
          reslove(false)
        }
      })
  })
}
